package com.java.netty.nio.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Author: Dgg
 * @Date: 2021/12/30 22:48
 */
public class GroupChatClient2 {
	//定义属性
	private final String host;
	private final Integer port;

	public GroupChatClient2(String host, Integer port) {
		this.host = host;
		this.port = port;
	}

	public void run() {
		EventLoopGroup eventExecutors = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap()
					.group(eventExecutors)
					.channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							//得到pipline
							ChannelPipeline pipeline = ch.pipeline();
							//加入hanlder
							pipeline.addLast("decoder", new StringDecoder());
							pipeline.addLast("encoder", new StringEncoder());
							//加入自定义handler
							pipeline.addLast(new GroupChantClientHandler());
						}
					});
			ChannelFuture sync = bootstrap.connect(host, port).sync();
			//得到channel
			Channel channel = sync.channel();
			System.out.println("--------" + channel.localAddress() + "------");
			//客户端输入信息 创建扫描器
			Scanner scanner = new Scanner(System.in);
			while (scanner.hasNextLine()) {
				String s = scanner.nextLine();
				//通过channel发送到服务器端
				channel.writeAndFlush(s);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			eventExecutors.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		GroupChatClient2 groupChatClient = new GroupChatClient2("127.0.0.1", 6667);
		groupChatClient.run();
	}
}
